package com.kakarote.examine.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.kakarote.core.common.cache.CrmCacheKey;
import com.kakarote.core.entity.UserInfo;
import com.kakarote.core.feign.admin.entity.SimpleUser;
import com.kakarote.core.feign.admin.service.AdminService;
import com.kakarote.core.feign.examine.entity.ExamineDataSaveBO;
import com.kakarote.core.feign.examine.entity.ExamineFlowVO;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.BaseUtil;
import com.kakarote.core.utils.UserUtil;
import com.kakarote.examine.constant.ExamineStatusEnum;
import com.kakarote.examine.constant.ExamineTypeEnum;
import com.kakarote.examine.entity.PO.*;
import com.kakarote.examine.mapper.ExamineFlowRoleMapper;
import com.kakarote.examine.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 审批流程角色审批记录表 服务实现类
 * </p>
 *
 * @author zhangzhiwei
 * @since 2020-11-13
 */
@Service("roleService")
public class ExamineFlowRoleServiceImpl extends BaseServiceImpl<ExamineFlowRoleMapper, ExamineFlowRole> implements IExamineFlowRoleService, ExamineTypeService {

    @Autowired
    private IExamineRecordService examineRecordService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private IExamineFlowFinalOptionalService examineFlowFinalOptionalService;

    @Autowired
    private IExamineFlowFinalService examineFlowFinalService;

    @Autowired
    private IExamineRecordLogService examineRecordLogService;


    /**
     * 保存额外的审批流程data对象
     *
     * @param dataSaveBO data
     * @param flowId     审批流程ID
     */
    @Override
    public void saveExamineFlowData(ExamineDataSaveBO dataSaveBO, Long flowId, String batchId) {
        ExamineFlowRole IExamineFlowRole = new ExamineFlowRole();
        IExamineFlowRole.setFlowId(flowId);
        IExamineFlowRole.setRoleId(CollectionUtil.join(dataSaveBO.getRoleIdList(), ","));
        IExamineFlowRole.setType(dataSaveBO.getType());
        IExamineFlowRole.setBatchId(batchId);
        save(IExamineFlowRole);
    }


    /**
     * 通过batchId查询所有flow关联对象
     *
     * @param map     缓存对象
     * @param batchId batchId
     */
    @Override
    public void queryFlowListByBatchId(Map<String, Object> map, String batchId) {
        List<ExamineFlowRole> continuousSuperiors = lambdaQuery().eq(ExamineFlowRole::getBatchId, batchId).list();
        Map<Long, List<ExamineFlowRole>> collect = continuousSuperiors.stream().collect(Collectors.groupingBy(ExamineFlowRole::getFlowId));
        map.put(ExamineTypeEnum.ROLE.getServerName(), collect);
    }

    /**
     * 查询详情页需要的审批详情
     *
     * @param examineFlow 当前审批流程
     * @param map         缓存的map
     * @return data
     */
    @Override
    @SuppressWarnings("unchecked")
    public ExamineFlowVO createFlowInfo(ExamineFlow examineFlow, Map<String, Object> map, List<UserInfo> userInfoList, Long ownerUserId) {
        Map<Long, List<ExamineFlowRole>> collect = (Map<Long, List<ExamineFlowRole>>) map.get(ExamineTypeEnum.ROLE.getServerName());
        List<ExamineFlowRole> flowRoles = collect.get(examineFlow.getFlowId());
        if (flowRoles == null || flowRoles.size() == 0) {
            return null;
        }
        ExamineFlowRole examineFlowRole = flowRoles.get(0);
        ExamineFlowVO examineFlowVO = new ExamineFlowVO();
        examineFlowVO.setType(examineFlowRole.getType());
        examineFlowVO.setName(examineFlow.getName());
        examineFlowVO.setExamineType(examineFlow.getExamineType());
        examineFlowVO.setFlowId(examineFlow.getFlowId());
        examineFlowVO.setExamineErrorHandling(examineFlow.getExamineErrorHandling());
        examineFlowVO.setRoleId(examineFlowRole.getRoleId());
        //0927 补充但钱的  角色相关信息
        if (ObjectUtil.isNotEmpty(examineFlowRole.getRoleId())) {
            List<Long> itemRoleList = StrUtil.split(examineFlowRole.getRoleId(), ',', -1, true, Long::valueOf);
            List<Map<String, Object>> roleList = adminService.listByRoleId(itemRoleList).getData();
            examineFlowVO.setRoleIdList(itemRoleList);
            examineFlowVO.setRoleList(roleList);
        }
        List<SimpleUser> userList = new ArrayList<>();
        List<Long> userIdList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            List<Long> itemRoleList = StrUtil.split(examineFlowRole.getRoleId(), ',', -1, true, Long::valueOf);
            Collection<Long> intersection = CollectionUtil.intersection(itemRoleList, userInfo.getRoles());
            if (!intersection.isEmpty()) {
                userIdList.add(userInfo.getUserId());
            }
        }
        userIdList = handleUserIdList(userIdList);
        for (Long userId : userIdList) {
            for (UserInfo userInfo : userInfoList) {
                if (Objects.equals(userInfo.getUserId(), userId)) {
                    userList.add(toSimPleUser(userInfo));
                    break;
                }
            }
        }
        examineFlowVO.setUserList(userList);
        return examineFlowVO;
    }

    /**
     * 处理当前节点
     *
     * @param examineFlow 当前处理节点
     * @param recordId    审核记录ID
     * @param data        特殊处理所需数据
     * @param examine     审核对象
     * @param init        是否初始化
     * @return data
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject disposeFlow(ExamineFlow examineFlow, Long recordId, Object data, Examine examine, boolean init) {
        ExamineFlowRole examineFlowRole = lambdaQuery().eq(ExamineFlowRole::getFlowId, examineFlow.getFlowId()).one();

        ExamineRecord examineRecord = examineRecordService.getById(recordId);

        examineFlow.setExamineId(examineRecord.getExamineId());
        ExamineFlowFinal examineFlowFinal = examineFlowFinalService.lambdaQuery().eq(ExamineFlowFinal::getFlowId, examineFlow.getFlowId())
                .eq(ExamineFlowFinal::getRecordId, recordId).one();
        if (examineFlowFinal == null) {
            Integer maxSort = examineFlowFinalService.getMaxSort(recordId, examineRecord.getExamineId());
            examineFlowFinal = new ExamineFlowFinal();
            examineFlowFinal.setName(examineFlow.getName());
            examineFlowFinal.setExamineType(examineFlow.getExamineType());
            examineFlowFinal.setFlowId(examineFlow.getFlowId());
            examineFlowFinal.setExamineErrorHandling(examineFlow.getExamineErrorHandling());
            examineFlowFinal.setCreateTime(new Date());
            examineFlowFinal.setCreateUserId(UserUtil.getUserId());
            examineFlowFinal.setExamineId(examineFlow.getExamineId());
            examineFlowFinal.setRecordId(recordId);
            examineFlowFinal.setType(examineFlowRole.getType());
            examineFlowFinal.setSort(maxSort + 1);
            examineFlowFinalService.save(examineFlowFinal);
        }

        List<Long> roleIds = StrUtil.split(examineFlowRole.getRoleId(), ',', -1, true, Long::valueOf);

        List<Long> userIdList = adminService.queryUserIdByRoleIds(roleIds).getData();

        List<ExamineFlowFinalOptional> userList = examineFlowFinalOptionalService.lambdaQuery().eq(ExamineFlowFinalOptional::getRecordId, recordId)
                .eq(ExamineFlowFinalOptional::getFlowId, examineFlow.getFlowId()).list();
        if (userList == null || userList.size() == 0) {
            userList = castFlowOptionalUser(userIdList, examineFlowRole.getFlowId(), recordId, examineFlowRole.getType());
            examineFlowFinalOptionalService.saveBatch(userList);
        }

        String batchId = IdUtil.simpleUUID();
        LocalDateTime now = LocalDateTimeUtil.now();
        List<ExamineRecordLog> recordLogs = new ArrayList<>();
        for (ExamineFlowFinalOptional examineFlowFinalUser : userList) {
            ExamineRecordLog examineRecordLog = new ExamineRecordLog();
            examineRecordLog.setLogId(BaseUtil.getNextId());
            examineRecordLog.setType(examineFlowFinal.getType());
            examineRecordLog.setCreateTime(now);
            examineRecordLog.setExamineTime(now);
            examineRecordLog.setUpdateTime(null);
            examineRecordLog.setCreateUserId(UserUtil.getUserId());
            examineRecordLog.setExamineId(examineFlowFinal.getExamineId());
            examineRecordLog.setExamineRoleId(0L);
            //   在这块判断审核人状态，是否有效等
            examineRecordLog.setExamineUserId(examineFlowFinalUser.getUserId());
            if (examineFlowFinal.getType() == 1) {
                if (userList.indexOf(examineFlowFinalUser) == 0) {
                    examineRecordLog.setExamineStatus(ExamineStatusEnum.UNDERWAY.getStatus());
                } else {
                    examineRecordLog.setExamineStatus(ExamineStatusEnum.AWAIT.getStatus());
                }
            } else {
                examineRecordLog.setExamineStatus(ExamineStatusEnum.UNDERWAY.getStatus());

            }
            if (ObjectUtil.isNotNull(examineFlowFinalUser.getUserId())) {
                BaseUtil.getRedis().del(CrmCacheKey.CRM_BACKLOG_NUM_CACHE_KEY + examineFlowFinalUser.getUserId().toString());
            }
            examineRecordLog.setFlowId(examineFlowFinal.getFlowId());
            examineRecordLog.setRecordId(recordId);
            examineRecordLog.setSort(examineFlowFinalUser.getSort());
            examineRecordLog.setBatchId(batchId);
            recordLogs.add(examineRecordLog);
        }
        examineRecordLogService.saveBatch(recordLogs);
        return new JSONObject().putOpt("status", ExamineStatusEnum.UNDERWAY.getStatus());
    }
}
